<?php
	
	require_once 'application/model.php';
    session_start();
	
	if(!isset($_SESSION['user'])) {
		header("Location:index.php");
	}
	$user = $_SESSION['user'];
	$post = $_GET['id'];
	
	$model = new Model();
	$model->newConnection( "localhost", "progin", "progin", "progin_171_13509027" );
	$queryAct = $model->cacheQuery("SELECT number_like FROM ngelike WHERE username = '$user' AND ID_post = $post");
	
	if($model->numRowsFromCache($queryAct) == 0) {
		$userAct = 0;
	} else {
		$temp = $model->resultsFromCache($queryAct);
		$userAct = $temp['number_like'];
	}
	
	$status = 1;
	if(!($_GET['act'] == $userAct)) {
		if($userAct == 0) {
			if($_GET['act'] == 1) {
				//insert like
				$model->executeQuery("INSERT INTO ngelike VALUES('$user',$post,1)");
			} else if($_GET['act'] == -1) {
				//insert dislike
				$model->executeQuery("INSERT INTO ngelike VALUES('$user',$post,-1)");
			}
		} else {
			if($_GET['act'] == 1) {
				//update dari dislike menjadi like
				$model->executeQuery("UPDATE ngelike SET number_like=1 WHERE username='$user' AND ID_post=$post");
			} else if($_GET['act'] == -1) {
				//update dari like menjadi dislike
				$model->executeQuery("UPDATE ngelike SET number_like=-1 WHERE username='$user' AND ID_post=$post");
			}
		}
		$status = 1;
	} else {
		$model->executeQuery("DELETE FROM ngelike WHERE username = '$user' AND ID_post = $post");
		$status = 0;
	}
	
	$queryNlike = $model->cacheQuery("SELECT id,li,dis  FROM (
		(SELECT ID_post AS id FROM post) AS t4 LEFT JOIN
		(SELECT t1.ID_post,li,dis FROM (
			(SELECT ID_post, COUNT(*) AS li FROM ngelike WHERE number_like=1 GROUP BY ID_post) AS t1 LEFT JOIN
			(SELECT ID_post, COUNT(*) AS dis FROM ngelike WHERE number_like=-1 GROUP BY ID_post) AS t2
			ON t1.ID_post=t2.ID_post 
			)
		) AS t3
		ON t3.ID_post=id
	) WHERE id = $post");
	
	$temp = $model->resultsFromCache($queryNlike);
	
	if(!isset($temp['li'])) $li = 0; else $li = $temp['li'];
	if(!isset($temp['dis'])) $dis = 0; else $dis = $temp['dis'];
	$nlike = $li-$dis;
	
	header('Content-type: text/xml');
	echo "<?xml version='1.0' encoding='ISO-8859-1'?>";
	echo "<likes>";
	echo"<id>". $post ."</id>";
	echo"<nlike>" . $nlike . "</nlike>";
	echo"<stat>" . $status . "</stat>";
	echo "</likes>";
?>